import pyperclip
import time
from datetime import datetime
import tkinter as tk
from tkinter import simpledialog, messagebox
import os
import json

class CitationAnnotator:
    def __init__(self):
        self.last_clipboard_content = ""
        self.citation_format = "{content}\n\n[引自: {source}, {time}]"
        self.settings_file = "citation_annotator_settings.json"
        self.log_file = "citation_annotator_log.txt"
        self.load_settings()
        
        # 初始化日志文件
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(f"\n\n=== 新的会话开始于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===\n")
    
    def log_operation(self, action, details):
        """记录操作到日志文件"""
        log_entry = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {action}: {details}\n"
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(log_entry)
    
    def load_settings(self):
        """加载用户设置"""
        if os.path.exists(self.settings_file):
            with open(self.settings_file, 'r', encoding='utf-8') as f:
                settings = json.load(f)
                self.citation_format = settings.get('citation_format', self.citation_format)
                self.default_source = settings.get('default_source', "未指定来源")
                self.log_file = settings.get('log_file', self.log_file)
        else:
            self.default_source = "未指定来源"
    
    def save_settings(self):
        """保存用户设置"""
        settings = {
            'citation_format': self.citation_format,
            'default_source': self.default_source,
            'log_file': self.log_file
        }
        with open(self.settings_file, 'w', encoding='utf-8') as f:
            json.dump(settings, f)
    
    def monitor_clipboard(self):
        """监控剪贴板内容变化"""
        root = tk.Tk()
        root.withdraw()  # 隐藏主窗口
        
        try:
            self.log_operation("系统", "开始监控剪贴板")
            
            while True:
                current_content = pyperclip.paste()
                
                if current_content != self.last_clipboard_content and current_content.strip():
                    self.last_clipboard_content = current_content
                    self.log_operation("剪贴板", f"检测到新内容: {current_content[:50]}...")  # 只记录前50个字符
                    
                    # 询问用户引文来源
                    source = simpledialog.askstring("引文来源", 
                                                  "请输入引文来源(期刊/书籍/网页等):", 
                                                  initialvalue=self.default_source)
                    
                    if source is None:  # 用户取消
                        self.log_operation("用户", "取消输入引文来源")
                        continue
                        
                    if source.strip():
                        self.default_source = source.strip()
                        self.save_settings()
                    
                    # 格式化引文
                    formatted_citation = self.format_citation(current_content, source)
                    self.log_operation("格式化", f"来源: {source}, 内容长度: {len(current_content)}")
                    
                    # 将格式化后的内容复制回剪贴板
                    pyperclip.copy(formatted_citation)
                    self.log_operation("系统", "已复制格式化内容到剪贴板")
                    
                    # 显示成功消息
                    messagebox.showinfo("成功", "引文已格式化并复制到剪贴板！\n\n" + formatted_citation[:200] + ("..." if len(formatted_citation) > 200 else ""))
                
                time.sleep(1)  # 每秒检查一次剪贴板
                
        except KeyboardInterrupt:
            self.log_operation("系统", "监控已停止")
            print("\n监控已停止")
        except Exception as e:
            self.log_operation("错误", f"发生异常: {str(e)}")
            messagebox.showerror("错误", f"发生错误: {str(e)}")
    
    def format_citation(self, content, source):
        """格式化引文为批注样式"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        formatted = self.citation_format.format(
            content=content.strip(),
            source=source,
            time=current_time
        )
        return formatted

def main():
    print("论文引文批注工具 - 正在运行...")
    print("当复制文本时，程序会提示你输入引文来源")
    print("然后自动格式化为批注样式并复制回剪贴板")
    print(f"所有操作将记录在 citation_annotator_log.txt 文件中")
    print("按Ctrl+C停止监控\n")
    
    annotator = CitationAnnotator()
    annotator.monitor_clipboard()

if __name__ == "__main__":
    main()
